import { Directive } from 'vue';
import { useUserStore } from '@/store/user';
import {useSimulateStore} from "@/store/simulate";
import {useBootStore} from "@/store/boot";

export const perm: Directive = {
    mounted(el, button) {
        toolPerm(el, button);
    },
    updated(el, button) {
        toolPerm(el, button);
    }
}

const toolPerm = (el:any, button:any) => {
    const userStore = useUserStore();
    const simulateStore = useSimulateStore();
    const bootStore = useBootStore();

    let permissions;
    if(bootStore.simulate){
        permissions = simulateStore.permissions;
    }else{
        permissions = userStore.permissions;
    }

    if (permissions == null || permissions.length <= 0) {
        return false;
    }

    if (button !== '' && button !== undefined) {
        const hasPerm = permissions.some((p) => {
            return p === button.value;
        });
        if (!hasPerm) {
            el.parentNode && el.parentNode.removeChild(el);
        }
    }
}